﻿package com._public._control 
{
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.system.LoaderContext;
	import flash.utils.ByteArray;
	/**
	 * 二进制相关操作
	 * @author WZH(shch8.com)
	 */
	public class ByteCtrl
	{
		private static var Instace:ByteCtrl=new ByteCtrl;
		public static function getInstance():ByteCtrl {
			return Instace;
		}
		/**
		 * 二进制插值
		 * @param	byteData	需要插值的二进制
		 * @param	keyStr		插入字符
		 * @param	keyPoint	插入位置
		 * @return
		 */
		public function insertByte(byteData:ByteArray,keyStr:String,keyPoint:uint):ByteArray {
			var _byteArray:ByteArray = new ByteArray;
			_byteArray.endian =byteData.endian;
			 for (var i:int = 0; i <= byteData.length; i++) {
				 if (i == keyPoint) {
					 _byteArray.writeUTF(keyStr);
					 }
				 _byteArray.writeByte(byteData[i]);
			 }
			return _byteArray;
		}
		/**
		 * 清除二进制值
		 * @param	encryptByte
		 * @param	keyStr
		 * @param	keyPoint
		 * @return
		 */
		public function clearByte(encryptByte:ByteArray,keyStr:String,keyPoint:uint,bytesFormat:Boolean=false):ByteArray {
			var j:uint;
			var keyArray:ByteArray = new ByteArray;
			keyArray.endian = encryptByte.endian;
			if (bytesFormat) {
				keyArray.writeUTFBytes(keyStr);
			}else {
			keyArray.writeUTF(keyStr);
				}
			var byte:ByteArray = new ByteArray;
			byte.endian = encryptByte.endian;
			for (var i:uint = 0; i < encryptByte.length-1; i++) {
					if (i == keyPoint) {
						if (encryptByte[i] == keyArray[0] && encryptByte[i + 1] == keyArray[1]) {
						i += keyArray.length;
						}else {//未找到需要清除的数据，返回原数据
						//	trace("未找到清除值")
							return encryptByte;
							}
					}
					byte.writeByte(encryptByte[i])
			 }
			return byte;
		}
		/**
		 * 二进制转Loader对象
		 * @param	byteData		
		 * @param	loadComplete	
		 * @return
		 */
		public function byteToLoader(byteData:ByteArray,loadComplete:Function=null):Loader {
			var ld:Loader = new Loader();
			ld.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, loadError);
			if (loadComplete is Function) ld.contentLoaderInfo.addEventListener(Event.COMPLETE, loadComp);
			var lc:Object = new LoaderContext();
			lc.allowCodeImport = true;
			ld.loadBytes(byteData,lc as LoaderContext);
			function loadComp(e:Event):void {
				loadComplete(ld);
				ld.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, loadError);
				ld.contentLoaderInfo.removeEventListener(Event.COMPLETE,loadComplete);
			}
			return ld;
		}
		private function loadError(e:IOErrorEvent):void {
			
		}
		
	}
	
}